package com.droowa.controller;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.droowa.domain.CompletePC;
import com.droowa.domain.OrderInfo;
import com.droowa.domain.OrderList;
import com.droowa.domain.OrderProduct;
import com.droowa.model.service.CancelManagementService;
import com.droowa.model.service.DeliveryEnterpriseManagementService;
import com.droowa.model.service.ExchangeManagementService;
import com.droowa.model.service.MileageOptionService;
import com.droowa.model.service.OrderService;
import com.droowa.model.service.PaymentManagementService;
import com.droowa.model.service.ProductManagementService;
import com.droowa.model.service.RefundManagementService;
import com.droowa.model.service.ReturnManagementService;
@Controller
@RequestMapping("/order/")
public class OrderController {
	
	@Autowired
	private OrderService orderService;
	
	//취소 교환 환불 반품 게시판 생성자
	@Autowired
	private CancelManagementService cMService;
	@Autowired
	private ExchangeManagementService eMService;
	@Autowired
	private RefundManagementService fMService;
	@Autowired
	private ReturnManagementService tMService;
	@Autowired
	private OrderService oService;
	@Autowired
	private ProductManagementService pMService;
	@Autowired
	private PaymentManagementService payService;
	@Autowired
	private DeliveryEnterpriseManagementService dEMService;
	@Autowired
	private MileageOptionService mOService;
	
//############################## 구매하기 ###################################
		@RequestMapping(value="orderForm.do")
		public String orderForm(OrderProduct pc, CompletePC completePC, String deliveryPrice, HttpServletRequest request, HttpSession session, ModelMap map) throws SQLException{
			session.setAttribute("OrderCompletePC", completePC);
			request.setAttribute("pc", pc);		//orderPage에 변경완료된 최종 상품 네임 바인딩
			session.setAttribute("orderPc", pc);
			request.setAttribute("paymentInfo", payService.getPaymentManagement());
			request.setAttribute("deliveryInfo", dEMService.getDeliveryEnterpriseManagement());
			request.setAttribute("mileageInfo", mOService.getMileageOption());
			//session.getAttribute("login_info"));//ID에 맞는 마일리지값 조회해와야 함
			
			if(session.getAttribute("login_info")!=null){
				session.setAttribute("OrderCompletePC", completePC);
				request.setAttribute("pc", pc);		//orderPage에 변경완료된 최종 상품 네임 바인딩
				session.setAttribute("orderPc", pc);
				request.setAttribute("paymentInfo", payService.getPaymentManagement());
				request.setAttribute("deliveryInfo", dEMService.getDeliveryEnterpriseManagement());
				System.out.println(mOService.getMileageOption());
				request.setAttribute("mileageInfo", mOService.getMileageOption());
				System.out.println(session.getAttribute("login_info"));//ID에 맞는 마일리지값 조회해와야 함
				return "customer.orderPage";
			}else{
				map.addAttribute("error_message", "로그인이 필요합니다");
				return "customer.login_form";
			}
		}
		@RequestMapping(value="order.do", method=RequestMethod.POST)
		public String order(OrderInfo orderInfo, int deliveryPrice, HttpSession session) throws SQLException{
			session.setAttribute("orderInfo", orderInfo);
			OrderProduct op = (OrderProduct)session.getAttribute("orderPc");

			op.setCompletePrice(String.valueOf(Integer.parseInt(op.getCompletePrice())+deliveryPrice));		//상품가격+배송비 해서 order Table에 insert
			oService.joinOrderProduct(op);									//orderTable에 orderProduct insert
			int a=orderService.joinOrderInfo(orderInfo);		// 최종 결제정보 insert
			HashMap map = (HashMap) pMService.getCompletePCById(op.getCompleteId());
			BigDecimal bd = (BigDecimal)map.get("CNT");
			int cnt = bd.intValue();
			oService.modifyOrderProductResultFalse(op.getCompleteId());
			pMService.modifyCompletePCCnt(op.getCompleteId(), ++cnt);		//해당 완제품 판매량++ Update
			
			CompletePC completePC = (CompletePC) session.getAttribute("OrderCompletePC");
			
			pMService.modifyProductQuantity(completePC.getCpuId());
			pMService.modifyProductQuantity(completePC.getMainboardId());
			pMService.modifyProductQuantity(completePC.getCoolerId());
			pMService.modifyProductQuantity(completePC.getMemoryId());
			pMService.modifyProductQuantity(completePC.getGraphicId());
			pMService.modifyProductQuantity(completePC.getHddId());
			pMService.modifyProductQuantity(completePC.getSsdId());
			pMService.modifyProductQuantity(completePC.getDvdId());
			pMService.modifyProductQuantity(completePC.getSoundId());
			pMService.modifyProductQuantity(completePC.getPowerId());
			pMService.modifyProductQuantity(completePC.getCaseId());
			pMService.modifyProductQuantity(completePC.getOsId());
			
			return "customer.orderSuccess";
		}
		
		@RequestMapping("orderDel.do")
		public String orderDel(OrderProduct orderProduct, HttpSession session) throws SQLException{
			System.out.println("삭제");
			String custId=orderProduct.getCustId();
			String completeId=orderProduct.getCompleteId();
			System.out.println(custId+completeId);
			oService.removeOrderProductById(custId, completeId);
			List<OrderProduct> order=orderService.getOrderListById(custId);
			session.setAttribute("shop", order);
			return "customer.shoppingCart_form";
		}
//######################### 고객게시판 로직  ###################################
		@RequestMapping(value="cancelManagement.do", method=RequestMethod.GET)
		public String getCancelManagement(HttpServletRequest request){   
			request.setAttribute("menu_category", "order");
			return "admin.order/cancel_management";
		}
		@RequestMapping(value="exchangeManagement.do", method=RequestMethod.GET)
		public String getExchangeManagement(HttpServletRequest request){   
			request.setAttribute("menu_category", "order");
			return "admin.order/exchange_management";
		}
		@RequestMapping(value="refundManagement.do", method=RequestMethod.GET)
		public String getRefundManagement(HttpServletRequest request){   
			request.setAttribute("menu_category", "order");
			return "admin.order/refund_management";
		}
		@RequestMapping(value="returnManagement.do", method=RequestMethod.GET)
		public String getReturnManagement(HttpServletRequest request){   
			request.setAttribute("menu_category", "order");
			return "admin.order/return_management";
		}
		
		@RequestMapping(value="getCancelManagement.do")
		public ModelAndView getCancelManagement(String enumerate, String search, String period, String startDate, String endDate,
				String stateorder, HttpServletRequest request, HttpSession session) throws Exception{
			request.setAttribute("menu_category", "order");
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			
			request.setAttribute("enumerate", enumerate);
			request.setAttribute("search", search);
			request.setAttribute("startDate", startDate);
			request.setAttribute("endDate", endDate);
			request.setAttribute("period", period);
			request.setAttribute("stateorder", stateorder);
			
			HashMap map = new HashMap();
			map.put("enumerate", enumerate);
			map.put("search", search);
			map.put("period", period);
			map.put("startDate", startDate);
			map.put("endDate", endDate+sdf.format(new Date()));
			map.put("stateorder", stateorder);
			
			List cancelManagementList = cMService.getCancelManagementByAll(map);			
			
			return new ModelAndView("admin.order/cancel_management", "cancelManagement_list", cancelManagementList);
		}
		
		@RequestMapping(value="getExchangeManagement.do")
		public ModelAndView getExchangeManagement(String enumerate, String search, String period, String startDate, String endDate,
				String stateorder, HttpServletRequest request, HttpSession session) throws Exception{
			request.setAttribute("menu_category", "order");
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			
			request.setAttribute("enumerate", enumerate);
			request.setAttribute("search", search);
			request.setAttribute("startDate", startDate);
			request.setAttribute("endDate", endDate);
			request.setAttribute("period", period);
			request.setAttribute("stateorder", stateorder);

			HashMap map = new HashMap();
			map.put("enumerate", enumerate);
			map.put("search", search);
			map.put("period", period);
			map.put("startDate", startDate);
			map.put("endDate", endDate+sdf.format(new Date()));
			map.put("stateorder", stateorder);
			
			List exchangeManagementList = eMService.getExchangeManagementByAll(map);			
			
			return new ModelAndView("admin.order/exchange_management", "exchangeManagement_list", exchangeManagementList);
		}
		
		@RequestMapping(value="getReturnManagement.do")
		public ModelAndView getReturnManagement(String enumerate, String search, String period, String startDate, String endDate,
				String stateorder, HttpServletRequest request, HttpSession session) throws Exception{
			request.setAttribute("menu_category", "order");
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			
			request.setAttribute("enumerate", enumerate);
			request.setAttribute("search", search);
			request.setAttribute("startDate", startDate);
			request.setAttribute("endDate", endDate);
			request.setAttribute("period", period);
			request.setAttribute("stateorder", stateorder);
			
			HashMap map = new HashMap();
			map.put("enumerate", enumerate);
			map.put("search", search);
			map.put("period", period);
			map.put("startDate", startDate);
			map.put("endDate", endDate+sdf.format(new Date()));
			map.put("stateorder", stateorder);
			
			List returnManagementList = tMService.getReturnManagementByAll(map);			
			
			return new ModelAndView("admin.order/return_management", "returnManagement_list", returnManagementList);
		}
		
		@RequestMapping(value="getRefundManagement.do")
		public ModelAndView getRefundManagement(String enumerate, String search, String period, String startDate, String endDate,
				String stateorder, HttpServletRequest request, HttpSession session) throws Exception{
			request.setAttribute("menu_category", "order");
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			
			request.setAttribute("enumerate", enumerate);
			request.setAttribute("search", search);
			request.setAttribute("startDate", startDate);
			request.setAttribute("endDate", endDate);
			request.setAttribute("period", period);
			request.setAttribute("stateorder", stateorder);
			
			HashMap map = new HashMap();
			map.put("enumerate", enumerate);
			map.put("search", search);
			map.put("period", period);
			map.put("startDate", startDate);
			map.put("endDate", endDate+sdf.format(new Date()));
			map.put("stateorder", stateorder);
			
			List refundManagementList = fMService.getRefundManagementByAll(map);			
			
			return new ModelAndView("admin.order/refund_management", "refundManagement_list", refundManagementList);
		}

		
		
		
		/*=====================Excel 파일 생성=======================
			@RequestMapping("managementView.do")
			public String businessRecordView(Map<String, Object> model, HttpSession session) throws SQLException{
				List<BusinessRecord> list = (List<BusinessRecord>)session.getAttribute("result");
				model.put("businessRecord", list);
				return "businessRecordView";
			}
			*/
		
}

